import os
import uuid
from typing import Optional, List, Dict, Any
from moviepy.editor import VideoFileClip, concatenate_videoclips, CompositeVideoClip, ImageClip, ColorClip
import tempfile
import json
from .llm_service import LLMService
from .ai_image_generator import AIImageGenerator  # 新增导入
from .audio_service import AudioService  # 新增音频服务
import logging
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import random

logger = logging.getLogger(__name__)

class AdvancedVideoGenerator:
    def __init__(self, llm_service: LLMService):
        self.llm_service = llm_service
        self.ai_image_generator = AIImageGenerator()  # 新增AI图像生成器
        self.audio_service = AudioService()  # 新增音频服务
        self.font_cache = {}    # 添加字体缓存
        
    def generate_advanced_video(self, prompt: str, output_path: str, project_id: Optional[str] = None, use_ai_images: bool = True, enable_audio: bool = True):
        """生成高级视频 - 合并AI图像和音频功能"""
        logger.info(f"🎬 开始生成高级视频，提示: {prompt}")
        
        try:
            # 确保输出目录存在
            os.makedirs(os.path.dirname(output_path), exist_ok=True)
            
            # 使用LLM改进提示并生成详细脚本
            improved_prompt = self.llm_service.improve_prompt(prompt)
            script = self.llm_service.generate_video_script(improved_prompt)
            
            logger.info(f"📜 生成的详细脚本")
            
            # 创建包含AI图像和音频的综合视频
            success = self._create_comprehensive_video(script, output_path, use_ai_images, enable_audio)
            
            # 验证视频文件
            if success and os.path.exists(output_path):
                file_size = os.path.getsize(output_path)
                logger.info(f"✅ 高级视频生成成功! 文件大小: {file_size} 字节")
                return True
            else:
                logger.error("❌ 视频文件未创建")
                return False
                
        except Exception as e:
            logger.error(f"❌ 高级视频生成失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return False

    def _create_comprehensive_video(self, script: Dict[str, Any], output_path: str, use_ai_images: bool = True, enable_audio: bool = True):
        """创建综合视频 - 合并AI图像和音频功能"""
        logger.info("🎬 开始创建综合视频...")
        
        video_clips = []
        
        try:
            # 1. 标题场景
            title_clip = self._create_unified_scene(
                script.get("title", "AI生成视频"),
                script.get("introduction", {}).get("visual_suggestions", ""),
                "title",
                3,
                use_ai_images
            )
            video_clips.append(title_clip)
            
            # 2. 介绍场景
            intro = script.get("introduction", {})
            intro_clip = self._create_unified_scene(
                intro.get("text", "视频介绍"),
                intro.get("visual_suggestions", ""),
                "introduction",
                min(intro.get("duration", 8), 10),
                use_ai_images
            )
            video_clips.append(intro_clip)
            
            # 3. 主体内容场景
            sections = script.get("sections", [])
            scene_types = ["contentA", "contentB", "highlight", "info"]
            
            for i, section in enumerate(sections):
                scene_type = scene_types[i % len(scene_types)]
                section_clip = self._create_unified_scene(
                    section.get("text", "内容部分"),
                    section.get("visual_suggestions", ""),
                    scene_type,
                    min(section.get("duration", 10), 15),
                    use_ai_images
                )
                video_clips.append(section_clip)
            
            # 4. 结尾场景
            conclusion = script.get("conclusion", {})
            conclusion_clip = self._create_unified_scene(
                conclusion.get("text", "感谢观看"),
                conclusion.get("visual_suggestions", ""),
                "conclusion",
                min(conclusion.get("duration", 5), 8),
                use_ai_images
            )
            video_clips.append(conclusion_clip)
            
            # 合并所有场景
            logger.info("🔗 合并视频场景...")
            final_video = concatenate_videoclips(video_clips, method="compose")
            
            # 添加音频
            if enable_audio:
                logger.info("🎵 添加音频...")
                final_video = self._add_audio_to_video(final_video, script)
            
            # 写入最终视频文件
            logger.info(f"💾 保存最终视频: {output_path}")
            final_video.write_videofile(
                output_path,
                fps=24,
                codec='libx264',
                audio_codec='aac',
                verbose=False,
                logger=None,
                threads=4
            )
            
            # 清理资源
            for clip in video_clips:
                clip.close()
            final_video.close()
            
            logger.info("✅ 综合视频创建完成")
            return True
            
        except Exception as e:
            # 清理资源
            for clip in video_clips:
                try:
                    clip.close()
                except:
                    pass
            logger.error(f"❌ 创建综合视频失败: {e}")
            return False

    def _create_unified_scene(self, text: str, visual_suggestions: str, scene_type: str, duration: int, use_ai_images: bool = True):
        """创建统一场景 - 结合AI图像和动态效果"""
        try:
            # 限制文本长度
            if len(text) > 500:
                text = text[:500] + "..."
            
            # 根据是否使用AI图像选择背景
            if use_ai_images and self.ai_image_generator.huggingface_token:
                # 尝试使用AI生成背景图像
                background = None
                try:
                    # 基于文本和视觉建议生成AI图像
                    ai_prompt = f"{text}. {visual_suggestions}" if visual_suggestions else text
                    ai_image = self.ai_image_generator.generate_image_for_scene(ai_prompt, "realistic")
                    
                    if ai_image:
                        # 调整图像尺寸以适应视频
                        ai_image = ai_image.resize((1280, 720), Image.LANCZOS)
                        background = ImageClip(np.array(ai_image), duration=duration)
                        logger.info("✅ 使用AI生成的背景图像")
                except Exception as e:
                    logger.warning(f"AI图像生成失败，使用动态背景: {e}")
            
            # 如果AI图像生成失败或未启用，使用动态背景
            if background is None:
                background = self._create_dynamic_background(scene_type, duration)
            
            # 创建文字层
            text_image = self._create_animated_text(text, duration, scene_type)
            text_clip = ImageClip(text_image, duration=duration)
            
            # 合成场景
            scene = CompositeVideoClip([background, text_clip])
            return scene
            
        except Exception as e:
            logger.error(f"❌ 创建统一场景失败: {e}")
            # 如果失败，返回纯色背景
            return ColorClip(size=(1280, 720), color=(100, 100, 200), duration=duration)

    def _create_audio_enhanced_video(self, script: Dict[str, Any], output_path: str, enable_audio: bool = True):
        """创建音频增强的视频"""
        logger.info("🎭 开始创建音频增强视频...")
        
        video_clips = []
        
        try:
            # 计算总视频时长
            total_duration = script.get("total_duration", 60)
            
            # 1. 标题场景
            title_clip = self._create_enhanced_scene(
                script.get("title", "AI生成视频"),
                "标题场景",
                3
            )
            video_clips.append(title_clip)
            
            # 2. 介绍场景
            intro = script.get("introduction", {})
            intro_clip = self._create_enhanced_scene(
                intro.get("text", "视频介绍"),
                "介绍场景",
                min(intro.get("duration", 8), 10)
            )
            video_clips.append(intro_clip)
            
            # 3. 主体内容场景
            sections = script.get("sections", [])
            scene_types = ["内容场景A", "内容场景B", "重点场景", "信息场景"]
            
            for i, section in enumerate(sections):
                scene_type = scene_types[i % len(scene_types)]
                section_clip = self._create_enhanced_scene(
                    section.get("text", "内容部分"),
                    scene_type,
                    min(section.get("duration", 10), 15)
                )
                video_clips.append(section_clip)
            
            # 4. 结尾场景
            conclusion = script.get("conclusion", {})
            conclusion_clip = self._create_enhanced_scene(
                conclusion.get("text", "感谢观看"),
                "结尾场景",
                min(conclusion.get("duration", 5), 8)
            )
            video_clips.append(conclusion_clip)
            
            # 合并所有场景
            logger.info("🔗 合并视频场景...")
            final_video = concatenate_videoclips(video_clips, method="compose")
            
            # 添加音频
            if enable_audio:
                logger.info("🎵 添加音频...")
                final_video = self._add_audio_to_video(final_video, script)
            
            # 写入最终视频文件
            logger.info(f"💾 保存最终视频: {output_path}")
            final_video.write_videofile(
                output_path,
                fps=24,
                codec='libx264',
                audio_codec='aac',
                verbose=False,
                logger=None,
                threads=4
            )
            
            # 清理资源
            for clip in video_clips:
                clip.close()
            final_video.close()
            
            logger.info("✅ 音频增强视频创建完成")
            return True
            
        except Exception as e:
            # 清理资源
            for clip in video_clips:
                try:
                    clip.close()
                except:
                    pass
            logger.error(f"❌ 创建音频增强视频失败: {e}")
            return False

    def _create_enhanced_scene(self, text: str, scene_type: str, duration: int):
        """创建增强的场景（带动态效果）"""
        try:
            # 限制文本长度
            if len(text) > 500:
                text = text[:500] + "..."
            
            # 根据场景类型选择背景
            background = self._create_dynamic_background(scene_type, duration)
            
            # 创建文字层
            text_image = self._create_animated_text(text, duration, scene_type)
            text_clip = ImageClip(text_image, duration=duration)
            
            # 合成场景
            scene = CompositeVideoClip([background, text_clip])
            return scene
            
        except Exception as e:
            logger.error(f"❌ 创建增强场景失败: {e}")
            # 如果失败，返回纯色背景
            return ColorClip(size=(1280, 720), color=(100, 100, 200), duration=duration)

    def _create_dynamic_background(self, scene_type: str, duration: int):
        """创建动态背景"""
        try:
            # 根据场景类型选择颜色方案
            color_schemes = {
                "标题场景": [(30, 30, 100), (60, 60, 150)],  # 蓝色系
                "介绍场景": [(60, 60, 120), (90, 90, 180)],  # 中蓝色系
                "内容场景A": [(80, 80, 140), (110, 110, 200)],  # 紫色系
                "内容场景B": [(70, 120, 70), (100, 150, 100)],  # 绿色系
                "重点场景": [(120, 80, 80), (150, 110, 110)],  # 红色系
                "信息场景": [(80, 120, 120), (110, 150, 150)],  # 青色系
                "结尾场景": [(30, 100, 30), (60, 130, 60)],  # 绿色系
            }
            
            colors = color_schemes.get(scene_type, [(100, 100, 200), (130, 130, 230)])
            
            # 创建简单的动态背景（颜色渐变）
            def make_frame(t):
                progress = t / duration
                
                # 在两个颜色之间渐变
                r = int(colors[0][0] + (colors[1][0] - colors[0][0]) * progress)
                g = int(colors[0][1] + (colors[1][1] - colors[0][1]) * progress)
                b = int(colors[0][2] + (colors[1][2] - colors[0][2]) * progress)
                
                frame = np.zeros((720, 1280, 3), dtype=np.uint8)
                frame[:, :] = [r, g, b]
                
                return frame
            
            from moviepy.video.VideoClip import VideoClip
            background = VideoClip(make_frame, duration=duration)
            return background
            
        except Exception as e:
            logger.error(f"❌ 创建动态背景失败: {e}")
            return ColorClip(size=(1280, 720), color=(100, 100, 200), duration=duration)

    def _create_animated_text(self, text: str, duration: int, scene_type: str):
        """创建带动画效果的文本"""
        frames = []
        
        for i in range(int(duration * 24)):  # 24fps
            t = i / 24.0
            progress = t / duration
            
            # 创建画布
            img = Image.new('RGBA', (1280, 720), (0, 0, 0, 0))
            draw = ImageDraw.Draw(img)
            
            # 加载字体
            font = self._get_font(36)
            
            # 文本分行
            lines = self._split_text_into_lines(text, max_width=1200, font=font)
            
            # 计算动画参数
            if scene_type == "标题场景":
                # 标题淡入效果
                opacity = int(255 * min(1.0, progress * 2))
                scale = 0.8 + 0.2 * progress
            elif scene_type == "结尾场景":
                # 结尾保持显示
                opacity = 255
                scale = 1.0
            else:
                # 内容场景滑入效果
                opacity = 255
                y_offset = int(50 * (1 - min(1.0, progress * 3)))
                scale = 1.0
            
            # 计算总高度和起始位置
            line_height = 45
            total_height = len(lines) * line_height
            start_y = (720 - total_height) // 2
            
            # 应用偏移（如果有）
            if 'y_offset' in locals():
                start_y += y_offset
            
            # 绘制每行文字
            for j, line in enumerate(lines):
                # 计算缩放后的文本尺寸
                bbox = draw.textbbox((0, 0), line, font=font)
                original_width = bbox[2] - bbox[0]
                scaled_width = int(original_width * scale)
                
                x = (1280 - scaled_width) // 2
                y = start_y + j * line_height
                
                # 添加文字阴影
                shadow_color = (0, 0, 0, opacity // 2)
                draw.text((x+2, y+2), line, font=font, fill=shadow_color)
                
                # 主文字
                text_color = (255, 255, 255, opacity)
                draw.text((x, y), line, font=font, fill=text_color)
            
            frames.append(np.array(img))
        
        # 返回第一帧（简化实现）
        return frames[0] if frames else np.array(Image.new('RGB', (1280, 720), (0, 0, 0)))

    def _add_audio_to_video(self, video_clip, script: dict):
        """为视频添加音频"""
        try:
            # 生成音频
            audio = self.audio_service.generate_audio_for_video(video_clip.duration, script)
            
            if audio:
                # 设置视频音频
                video_with_audio = video_clip.set_audio(audio)
                logger.info("✅ 音频添加成功")
                return video_with_audio
            else:
                logger.warning("无法添加音频，返回原视频")
                return video_clip
                
        except Exception as e:
            logger.error(f"❌ 添加音频失败: {e}")
            return video_clip
        
    def _create_ai_enhanced_video(self, script: Dict[str, Any], output_path: str, use_ai_images: bool = True):
        """创建AI增强的视频"""
        logger.info("🎭 开始创建AI增强视频...")
        
        video_clips = []
        
        try:
            # 1. 标题场景（使用AI图像）
            title_clip = self._create_ai_enhanced_scene(
                script.get("title", "AI生成视频"),
                script.get("introduction", {}).get("visual_suggestions", ""),
                3,
                use_ai_images
            )
            video_clips.append(title_clip)
            
            # 2. 介绍场景
            intro = script.get("introduction", {})
            intro_clip = self._create_ai_enhanced_scene(
                intro.get("text", "视频介绍"),
                intro.get("visual_suggestions", ""),
                min(intro.get("duration", 8), 10),
                use_ai_images
            )
            video_clips.append(intro_clip)
            
            # 3. 主体内容场景
            sections = script.get("sections", [])
            for i, section in enumerate(sections):
                section_clip = self._create_ai_enhanced_scene(
                    section.get("text", "内容部分"),
                    section.get("visual_suggestions", ""),
                    min(section.get("duration", 10), 15),
                    use_ai_images
                )
                video_clips.append(section_clip)
            
            # 4. 结尾场景
            conclusion = script.get("conclusion", {})
            conclusion_clip = self._create_ai_enhanced_scene(
                conclusion.get("text", "感谢观看"),
                conclusion.get("visual_suggestions", ""),
                min(conclusion.get("duration", 5), 8),
                use_ai_images
            )
            video_clips.append(conclusion_clip)
            
            # 合并所有场景
            logger.info("🔗 合并视频场景...")
            final_video = concatenate_videoclips(video_clips, method="compose")
            
            # 写入最终视频文件
            logger.info(f"💾 保存最终视频: {output_path}")
            final_video.write_videofile(
                output_path,
                fps=24,
                codec='libx264',
                audio_codec='aac',
                verbose=False,
                logger=None,
                threads=4
            )
            
            # 清理资源
            for clip in video_clips:
                clip.close()
            final_video.close()
            
            logger.info("✅ AI增强视频创建完成")
            
        except Exception as e:
            # 清理资源
            for clip in video_clips:
                try:
                    clip.close()
                except:
                    pass
            raise e

    def _create_ai_enhanced_scene(self, text: str, visual_suggestions: str, duration: int, use_ai_images: bool = True):
        """创建AI增强的场景"""
        try:
            # 限制文本长度
            if len(text) > 500:
                text = text[:500] + "..."
                
            # 尝试使用AI生成背景图像
            background = None
            if use_ai_images and self.ai_image_generator.huggingface_token:
                try:
                    # 基于文本和视觉建议生成AI图像
                    ai_prompt = f"{text}. {visual_suggestions}" if visual_suggestions else text
                    ai_image = self.ai_image_generator.generate_image_for_scene(ai_prompt, "realistic")
                    
                    if ai_image:
                        # 调整图像尺寸以适应视频
                        ai_image = ai_image.resize((1280, 720), Image.LANCZOS)
                        background = ImageClip(np.array(ai_image), duration=duration)
                        logger.info("✅ 使用AI生成的背景图像")
                except Exception as e:
                    logger.warning(f"AI图像生成失败，使用颜色背景: {e}")
            
            # 如果AI图像生成失败或未启用，使用颜色背景
            if background is None:
                # 基于文本生成确定性颜色
                bg_color = self._get_deterministic_color(text)
                background = ColorClip(size=(1280, 720), color=bg_color, duration=duration)
            
            # 创建文字层
            text_image = self._create_text_image(text, (0, 0, 0) if use_ai_images else (255, 255, 255))
            text_clip = ImageClip(text_image, duration=duration)
            
            # 合成场景
            scene = CompositeVideoClip([background, text_clip])
            return scene
            
        except Exception as e:
            logger.error(f"❌ 创建AI增强场景失败: {e}")
            # 如果失败，返回纯色背景
            return ColorClip(size=(1280, 720), color=(100, 100, 200), duration=duration)

    def _get_deterministic_color(self, text: str) -> tuple:
        """基于文本生成确定性颜色"""
        # 使用文本的哈希值来生成确定性颜色
        hash_val = hash(text) % 360  # 使用0-359度的色相
        
        # 将HSV转换为RGB
        import colorsys
        r, g, b = colorsys.hsv_to_rgb(hash_val / 360.0, 0.7, 0.8)  # 饱和度0.7，亮度0.8
        
        return (int(r * 255), int(g * 255), int(b * 255))

    def _create_simplified_multi_scene_video(self, script: Dict[str, Any], output_path: str):
        """创建简化的多场景视频 - 修复版"""
        logger.info("🎭 开始创建多场景视频...")
        
        video_clips = []
        
        try:
            # 1. 标题场景
            title_clip = self._create_simple_scene(
                script.get("title", "AI生成视频"),
                (30, 30, 100),  # 深蓝色背景
                3
            )
            video_clips.append(title_clip)
            
            # 2. 介绍场景
            intro = script.get("introduction", {})
            intro_clip = self._create_simple_scene(
                intro.get("text", "视频介绍"),
                (60, 60, 120),  # 中蓝色背景
                min(intro.get("duration", 8), 10)  # 限制最大时长
            )
            video_clips.append(intro_clip)
            
            # 3. 主体内容场景
            sections = script.get("sections", [])
            colors = [
                (80, 80, 140),   # 紫色
                (70, 120, 70),   # 绿色
                (120, 80, 80),   # 红色
                (80, 120, 120),  # 青色
            ]
            
            for i, section in enumerate(sections):
                section_clip = self._create_simple_scene(
                    section.get("text", "内容部分"),
                    colors[i % len(colors)],
                    min(section.get("duration", 10), 15)  # 限制最大时长
                )
                video_clips.append(section_clip)
            
            # 4. 结尾场景
            conclusion = script.get("conclusion", {})
            conclusion_clip = self._create_simple_scene(
                conclusion.get("text", "感谢观看"),
                (30, 100, 30),  # 绿色背景
                min(conclusion.get("duration", 5), 8)  # 限制最大时长
            )
            video_clips.append(conclusion_clip)
            
            # 合并所有场景
            logger.info("🔗 合并视频场景...")
            final_video = concatenate_videoclips(video_clips, method="compose")
            
            # 写入最终视频文件
            logger.info(f"💾 保存最终视频: {output_path}")
            final_video.write_videofile(
                output_path,
                fps=24,
                codec='libx264',
                audio_codec='aac',
                verbose=False,
                logger=None,
                threads=4  # 使用多线程加速
            )
            
            # 清理资源
            for clip in video_clips:
                clip.close()
            final_video.close()
            
            logger.info("✅ 多场景视频创建完成")
            
        except Exception as e:
            # 清理资源
            for clip in video_clips:
                try:
                    clip.close()
                except:
                    pass
            raise e

    def _create_simple_scene(self, text: str, bg_color: tuple, duration: int):
        """创建简单场景 - 修复版"""
        try:
            # 限制文本长度
            if len(text) > 500:
                text = text[:500] + "..."
                
            # 创建背景
            background = ColorClip(size=(1280, 720), color=bg_color, duration=duration)
            
            # 使用PIL创建文字图像
            text_image = self._create_text_image(text, bg_color)
            text_clip = ImageClip(text_image, duration=duration)
            
            # 合成场景
            scene = CompositeVideoClip([background, text_clip])
            return scene
            
        except Exception as e:
            logger.error(f"❌ 创建场景失败: {e}")
            # 如果失败，返回纯色背景
            return ColorClip(size=(1280, 720), color=bg_color, duration=duration)

    def _create_text_image(self, text: str, bg_color: tuple):
        """创建文字图像 - 修复版"""
        try:
            # 创建图像
            width, height = 1280, 720
            img = Image.new('RGB', (width, height), color=bg_color)
            draw = ImageDraw.Draw(img)
            
            # 加载字体
            font = self._get_font(36)
            
            # 文本分行
            lines = self._split_text_into_lines(text, max_width=1200, font=font)
            
            # 计算总高度
            line_height = 45
            total_height = len(lines) * line_height
            start_y = (height - total_height) // 2
            
            # 绘制每行文字
            for i, line in enumerate(lines):
                bbox = draw.textbbox((0, 0), line, font=font)
                text_width = bbox[2] - bbox[0]
                x = (width - text_width) // 2
                y = start_y + i * line_height
                
                # 添加文字阴影（轻微偏移）
                shadow_color = (0, 0, 0)
                draw.text((x+2, y+2), line, font=font, fill=shadow_color)
                
                # 主文字
                text_color = self._get_text_color(bg_color)
                draw.text((x, y), line, font=font, fill=text_color)
            
            return np.array(img)
            
        except Exception as e:
            logger.error(f"❌ 创建文字图像失败: {e}")
            # 返回纯色图像作为后备
            img = Image.new('RGB', (1280, 720), color=bg_color)
            return np.array(img)

    def _get_font(self, size: int):
        """获取字体 - 带缓存版本"""
        # 限制字体大小范围
        size = max(12, min(72, size)) # 限制在12-72之间
        
        cache_key = f"{size}"
        
        if cache_key in self.font_cache:
            return self.font_cache[cache_key]
        
        try:
            # 字体路径列表（按优先级排序）
            # 使用绝对路径
            import os
            current_dir = os.path.dirname(os.path.abspath(__file__))
            font_paths = [
                # 1. 项目本地字体（最高优先级）
                os.path.join(current_dir, "fonts", "simhei.ttf"),      # 黑体
                os.path.join(current_dir, "fonts", "msyh.ttc"),        # 微软雅黑
                os.path.join(current_dir, "fonts", "simsun.ttc"),      # 宋体
                
                # 2. Windows系统字体
                "C:/Windows/Fonts/simhei.ttf",    # 黑体
                "C:/Windows/Fonts/msyh.ttc",      # 微软雅黑
                "C:/Windows/Fonts/msyhbd.ttc",    # 微软雅黑粗体
                "C:/Windows/Fonts/simsun.ttc",    # 宋体
                "C:/Windows/Fonts/simkai.ttf",    # 楷体
                "C:/Windows/Fonts/simfang.ttf",   # 仿宋
                
                # 3. 备用英文字体
                os.path.join(current_dir, "fonts", "arial.ttf"),
                "C:/Windows/Fonts/arial.ttf",
                "C:/Windows/Fonts/times.ttf",
            ]
            
            for font_path in font_paths:
                try:
                    if os.path.exists(font_path):
                        font = ImageFont.truetype(font_path, size)
                        logger.info(f"✅ 加载字体: {font_path}")
                        
                        # 加载成功后缓存
                        self.font_cache[cache_key] = font
                        return font
                except OSError as e:
                    logger.debug(f"字体文件不存在或损坏：{font_path} - {e}")
                    continue
                except Exception as e:
                    logger.debug(f"字体加载异常 {font_path}: {e}")
                    continue
            
            # 如果所有字体都失败，使用默认字体
            logger.warning("所有字体加载失败，使用默认字体")
            return ImageFont.load_default()
            
        except Exception as e:
            logger.error(f"字体加载异常: {e}")
            return ImageFont.load_default()

    def _get_text_color(self, bg_color: tuple):
        """根据背景颜色获取合适的文字颜色"""
        # 计算背景亮度
        brightness = (bg_color[0] * 0.299 + bg_color[1] * 0.587 + bg_color[2] * 0.114)
        
        # 如果背景较暗，使用白色文字；否则使用黑色文字
        if brightness < 128:
            return (255, 255, 255)  # 白色
        else:
            return (0, 0, 0)  # 黑色

    def _split_text_into_lines(self, text: str, max_width: int, font):
        """将文本分割成多行 - 修复版"""
        try:
            words = text.split()
            lines = []
            current_line = []
            
            for word in words:
                test_line = ' '.join(current_line + [word])
                
                # 估算文本宽度
                bbox = ImageDraw.Draw(Image.new('RGB', (1, 1))).textbbox((0, 0), test_line, font=font)
                text_width = bbox[2] - bbox[0]
                
                if text_width <= max_width:
                    current_line.append(word)
                else:
                    if current_line:
                        lines.append(' '.join(current_line))
                    current_line = [word]
            
            if current_line:
                lines.append(' '.join(current_line))
            
            # 如果行数太多，截断
            if len(lines) > 8:
                lines = lines[:8]
                if len(lines[-1]) > 50:
                    lines[-1] = lines[-1][:47] + "..."
            
            return lines
            
        except Exception as e:
            logger.error(f"❌ 文本分行失败: {e}")
            # 简单的分行作为后备
            return [text[i:i+50] for i in range(0, min(len(text), 400), 50)]
